<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\model\AppConfig;
use app\common\model\UserScoreRecord;
use app\common\service\GlobalsVariableService;
use app\common\service\UserService;
use app\common\service\WxService;

class Sign
{
    /**
     * 积分信息
     * @param $param
     * @return array
     */
    public function info($param): array
    {
        // 提取参数
        $userId = $param['userId'];
        $appId = getAppId();

        // 查询用户信息
        $user = app(UserService::class)->getUserById($userId);

        // 查询积分记录
        $scoreActivity = new ScoreActivity();
        $scoreActivity->initConfig($appId);
        $recordModel = new UserScoreRecord();
        $resData = [
            'score' => $user['score'],
            'user_id' => $userId,
            'score_in' => $recordModel->getTodayCountByUid($userId, 1),
            'score_out' => $recordModel->getTodayCountByUid($userId, 2),
            'is_sign' => $recordModel->checkTodaySign($userId) ? 1 : 0,
            'is_bind_wx' => $user['openid'] ? 1 : 0,
            'is_bind_mp' => $recordModel->checkSource($userId, 11) ? 1 : 0,
            'is_bind_email' => $user['email'] ? 1 : 0,
            'is_bind_mobile' => $user['mobile'] ? 1 : 0,
            'is_desktop' => $recordModel->checkSource($userId, 9) ? 1 : 0,
            'is_watch_video' => !$recordModel->checkTodayReward($userId) ? 1 : 0,
            //'is_bind_wx_group' => $recordModel->checkSource($userId, 13),
            'is_bind_wx_group' => true,
            'record_list' => $recordModel->getListByUid($userId),
            'wx_number' => $scoreActivity->source_map['3']['score'],
            'mail_number' => $scoreActivity->source_map['4']['score'],
            'sign_number' => $scoreActivity->source_map['6']['score'], // 签到赠送基数
            'video_count' => 10000, // 视频赠送次数
            'mp_number' => $scoreActivity->source_map['11']['score'], // 公众号赠送基数
            'mp_sign_number' => $scoreActivity->source_map['14']['score'], // 公众号签到基数
            'video_number' => $scoreActivity->source_map['8']['score'], // 视频赠送基数
            'share_number' => $scoreActivity->source_map['5']['score'], // 分享赠送基数
            'share_file_number' => '500', // 分享学习资料赠送积分
            'bind_wx_group_num' => $scoreActivity->source_map['13']['score'], // 分享学习资料赠送积分
            'add_desktop_number' => $scoreActivity->source_map['9']['score'], // 添加到小程序桌面
            'add_my_app_number' => $scoreActivity->source_map['10']['score'], // 添加到我的小程序
            'bind_mobile_number' => $scoreActivity->source_map['11']['score'], // 绑定手机号
        ];

        // 填充数据
        if ($resData['score_in'] > 0) {
            $resData['score_in'] = "+{$resData['score_in']}";
        }
        if ($resData['score_out'] > 0) {
            $resData['score_out'] = "-{$resData['score_out']}";
        }

        // 填充附加说明
        $config = $scoreActivity->getConfig();
        $resData['att_desc_list'] = $config['rule_tip_list'] ?? [];

        //返回
        return $resData;
    }

    /**
     * 确认签到
     * @param $param
     * @throws BusinessException
     */
    public function confirm($param, $checkCode = true)
    {
        // 提取参数
        $code = $param['code'] ?? '';
        $userId = $param['userId'];
        $appId = GlobalsVariableService::get('appId');

        // 安全校验
        if ($checkCode) {
            if (!$code) {
                throw new BusinessException('数据异常');
            }

            // Code校验
            checkSafeByWxCode($appId, $code);
        }

        // 检查是否已签
        $model = new UserScoreRecord();
        if ($model->checkTodaySign($userId)) {
            throw new BusinessException('今日已签到');
        }

        // 检查昨天是否已签
        $is_continue = $model->checkYesTodaySign($userId);

        // 赠送积分
        $source = $is_continue ? 7 : 6;
        app(ScoreActivity::class)->initConfig($appId)->send($userId, $source);

        // 自动过白
        $model = new UserScoreRecord();
        if ($model->checkCount($userId, 6) > 10) {
            app(UserService::class)->setUserToWhitelist($userId);
        }
    }

    /**
     * 公众号确认签到
     * @throws BusinessException
     */
    public function mpConfirm($userId)
    {
        // 检查是否已签
        $source = 14;
        $model = new UserScoreRecord();
        if ($model->getTodayCount($userId, [14])) {
            throw new BusinessException('今日已签到');
        }

        // 赠送积分
        $appId = getAppId();
        $scoreActivity = app(ScoreActivity::class)->initConfig($appId);
        $scoreActivity->send($userId, $source);

        // 自动过白
        $model = new UserScoreRecord();
        if ($model->checkCount($userId, $source) > 10) {
            app(UserService::class)->setUserToWhitelist($userId);
        }

        // 返回
        return $scoreActivity->source_map[$source]['score'] ?? 0;
    }

    /**
     * 确认激励视频
     * @param $param
     * @throws BusinessException
     */
    public function rewardConfirm($param)
    {
        // 提取参数
        $code = $param['code'];
        $userId = $param['userId'];
        $appId = GlobalsVariableService::get('appId');

        // 安全校验
        if ($code) {
            checkSafeByWxCode($appId, $code);
        }

        // 自动过白
        $model = new UserScoreRecord();
        if ($model->checkCount($userId, 8) > 10) {
            app(UserService::class)->setUserToWhitelist($userId);
        }

        // 赠送积分
        app(ScoreActivity::class)->initConfig($appId)->send($userId, 8);
    }

    /**
     * wxGroupWelfare
     * @param array $param
     * @return mixed
     * @throws BusinessException
     */
    public function wxGroupWelfare(array $param)
    {
        // 提取参数
        $iv = $param['iv'];
        $code = $param['code'];
        $userId = $param['userId'];
        $appId = GlobalsVariableService::get('appId');
        $encryptedData = $param['encryptedData'];

        // 查询微信用户信息
        $wx = new WxService();
        $wx->setAppId($appId);
        $wxGroupKey = 'opengid';
        $wxInfo = $wx->decryptData($code, $iv, $encryptedData);
        if (empty($wxInfo[$wxGroupKey])) {
            throw new BusinessException('获取微信群信息失败');
        }

        // 保存日志
        //$log = $userId . '--' . $wxInfo[$wxGroupKey] . PHP_EOL;
        //Log::record($log);

        // 检查微信群是否允许
        $config = app(AppConfig::class)->getByIdAndType($appId, 'wx_group');
        $wx_group_gid_list = app(AppConfig::class)->listValueToArray($config['wx_group_gid']);
        if (!in_array($wxInfo[$wxGroupKey], $wx_group_gid_list)) {
            throw new BusinessException('请从官方群入口领取福利');
        }

        // 赠送积分
        $check_pass = app(ScoreActivity::class)->initConfig($appId)->send($userId, 13);
        if (!$check_pass) {
            throw new BusinessException('您已经领取过此福利');
        }

        // 返回
        return $wxInfo[$wxGroupKey];
    }
}